<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/9/11
 * Time: 1:35 PM
 */
namespace Core\common;

class Wechat
{
    use \Core\Traits\Wechat;

    /**
     * @param string $url
     * @return mixed
     */
    public static function getJsSdk($url = '')
    {
        try{
            $account_api = \WeAccount::create();
            $sdk = $account_api->getJssdkConfig($url);

            return $sdk;
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }

    /**
     * 微信网页授权
     * @param string $scope
     * @param bool $refresh
     * @return mixed
     */
    public static function oauth2($scope = 'userinfo',$refresh = false)
    {
        $code = I('code');
        $url  = Request::url();
        $oauthType   = Assist::globalVal('oauth_account.type');
        $oauthAppId  = Assist::globalVal('oauth_account.key');
        $sessionOpenidKey = $oauthAppId.'__openid__';

        if($refresh === false){
            $openid = $_SESSION[$sessionOpenidKey];
            if($openid){
                $_userInfoKey = '__wechat_user_info_'.$openid.'__';
                $userInfo = Cache::get($_userInfoKey);
                if($userInfo){
                    $userInfo['_isCache'] = 1;
                    return $userInfo;
                }
            }
        }
        if(empty($code)){
            self::authRedirect($oauthAppId,$url,$scope,$oauthType);
        }

        $oauthAppSecret = Assist::globalVal('oauth_account.secret');
        $userInfo = self::oauth2UserInfo($oauthAppId,$oauthAppSecret,$code,$oauthType);
        $_SESSION[$sessionOpenidKey] = $userInfo['openid'];
        $_userInfoKey = '__wechat_user_info_'.$userInfo['openid'].'__';
        Cache::set($_userInfoKey,$userInfo,86400*7);

        return $userInfo;
    }
}